//
//  TMShoppingCartController.m
//  国学商家管理
//
//  Created by Tao Li on 2018/6/29.
//  Copyright © 2018年 mac. All rights reserved.
//

#import "TMShoppingCartController.h"
#import "TMShopListCell.h"
#import "TMUserViewModel.h"
#import "TMMyCourseModel.h"
#import "UIAlertController+SPAlert.h"
#import "WZNoResultView.h"
#import "TMBuyGoodsController.h"
#import "TMCommodityDetailController.h"
@interface TMShoppingCartController ()<UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *shoppingTab;
@property (weak, nonatomic) IBOutlet UIView *shoppingBarView;
@property (weak, nonatomic) IBOutlet UILabel *totalPriceLabel;
@property (nonatomic, strong) NSMutableArray *shopsCountArray;
@property (nonatomic, strong) NSMutableArray *resultArray;
@property (weak, nonatomic) IBOutlet UIButton *calculateBtn;

@property (nonatomic, assign) BOOL is_checkAll;
@property (nonatomic, assign) BOOL canCheckAll;
@property (weak, nonatomic) IBOutlet UIButton *checkAllBtn;
@property (weak, nonatomic) IBOutlet UIButton *deleteAllBtn;
@property (nonatomic, strong) TMUserViewModel *viewModel;
@property (nonatomic, strong) WZNoResultView *noResultView;
@end

@implementation TMShoppingCartController
- (WZNoResultView *)noResultView{
    if (!_noResultView) {
        _noResultView = [[[NSBundle mainBundle] loadNibNamed:@"WZNoResultView" owner:nil options:nil]firstObject];
        if (kWindowH == 812.0) {
            _noResultView.frame = CGRectMake(0, 0, kWindowW, kWindowH);
        }else {
            _noResultView.frame = CGRectMake(0, 0, kWindowW, kWindowH);
        }
        _noResultView.isSearchVC = YES;
        [self.shoppingTab addSubview:_noResultView];
    }
    return _noResultView;
}
- (void)noResultViewShowORNot{
    if (!self.shopsCountArray.count) {
        self.noResultView.hidden = NO;
    }else{
        self.noResultView.hidden = YES;
    }
}
-(NSMutableArray*)shopsCountArray{
    if (_shopsCountArray == nil) {
        _shopsCountArray = [NSMutableArray array];
    }
    return _shopsCountArray;
}
-(NSMutableArray*)resultArray{
    if (_resultArray == nil) {
        _resultArray = [NSMutableArray array];
    }
    return _resultArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"购物车";
    self.shoppingTab.delegate = self;
    self.shoppingTab.dataSource = self;
    self.shoppingTab.tableFooterView = [UIView new];
    self.canCheckAll = YES;
    self.deleteAllBtn.hidden = NO;
    [self displayStates:self.canCheckAll];
//    [self displayRightItem: @"编辑"];
    self.viewModel = [[TMUserViewModel alloc]init];
    self.shoppingTab.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self.viewModel  getShoppingCartSuccess:^(id responseObject) {
            self.shopsCountArray = responseObject;
            [self.shoppingTab reloadData];
            [self.shoppingTab.mj_header endRefreshing];
            [self noResultViewShowORNot];
        } failed:^(NSString *error) {
            [self.shoppingTab reloadData];
            [self.shoppingTab.mj_header endRefreshing];
             [self noResultViewShowORNot];
        }];
    }];
    [self.shoppingTab.mj_header beginRefreshing];
}

- (void)displayRightItem:(NSString *)str{
    UIBarButtonItem *letfItem = [[UIBarButtonItem alloc]initWithTitle:str  style:UIBarButtonItemStylePlain target:self action:@selector(addTeacher)];
    self.navigationItem.rightBarButtonItem = letfItem;
    //self.canCheckAll = !self.canCheckAll;
}
- (void)addTeacher{
    if (!self.shopsCountArray.count) {
        return;
    }
    [self displayStates:self.canCheckAll];
     [self.shoppingTab reloadData];
}
- (void)displayStates:(BOOL)iscan{
    [self.resultArray removeAllObjects];
    if (self.canCheckAll == NO) {
        //self.checkAllBtn.userInteractionEnabled = YES;
       // [self displayRightItem:@"取消"];
        self.canCheckAll = YES;
        //self.deleteAllBtn.hidden = YES;
    }else
    {
        //self.checkAllBtn.userInteractionEnabled = NO;
       // [self displayRightItem:@"编辑"];
        self.canCheckAll = NO;
        //self.is_checkAll = NO;
       // _checkAllBtn.selected = NO;
       // self.deleteAllBtn.hidden = NO;
        
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.shopsCountArray.count;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    TMShopListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TMShopListCell" forIndexPath:indexPath];
    TMMyCartModel *models = self.shopsCountArray[indexPath.row];
    cell.model = models;
    cell.checkListBtn.hidden = NO;
    cell.leftConst.constant = 42;
    if (self.canCheckAll == NO) {
        if (self.is_checkAll == NO) {
            cell.checkListBtn.selected = NO;
        }else{
            cell.checkListBtn.selected = YES;
        }
    }else{
        cell.checkListBtn.selected = YES;
    }
    cell.checkBlock = ^(BOOL isCheck){
        if (isCheck == YES) {
             [self.resultArray addObject:models];
            
        }else{
            [self.resultArray removeObject:models];
             self.checkAllBtn.selected = NO;
            self.canCheckAll = YES;
            self.is_checkAll = NO;
        }
//        if (self.is_checkAll == YES) {
//            //全选了 之后 取消某一个或者多个
//            if (isCheck == NO) {
//                [self.resultArray removeObject:models];
//                if (self.resultArray.count == 0) {
//                    self.checkAllBtn.selected = NO;
//                }
//            }
//        }
        float totalMoney = 0.0;
        for (TMMyCartModel *models in self.resultArray) {
            totalMoney = models.price + totalMoney;
        }
        self.totalPriceLabel.text = [NSString stringWithFormat:@"%.02f元", totalMoney];
        
    };
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 96;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    TMMyCartModel *models = self.shopsCountArray[indexPath.row];
    TMCommodityDetailController *vc = [[UIStoryboard storyboardWithName:@"Nearby" bundle:nil] instantiateViewControllerWithIdentifier:@"TMCommodityDetailController"];
    vc.rid = models.cid;
    [self.navigationController pushViewController:vc animated:YES];
}
- (IBAction)shopAllAction:(UIButton *)sender {
    sender.selected = !sender.selected;
    self.is_checkAll = sender.selected;
    self.canCheckAll = sender.selected;
    [self.resultArray removeAllObjects];
    if (sender.selected == YES) {
        [self.resultArray addObjectsFromArray:self.shopsCountArray];
        //计算全部钱。
        float totalMoney = 0.0;
        for (TMMyCartModel *models in self.resultArray) {
            totalMoney = models.price + totalMoney;
        }
        self.totalPriceLabel.text = [NSString stringWithFormat:@"%.02f元", totalMoney];
    }else{
     [self.resultArray removeAllObjects];
        self.totalPriceLabel.text = @"0.00元";
    }
    [self.shoppingTab reloadData];
}
- (IBAction)goShoppingAction:(UIButton *)sender {
    if (!self.resultArray.count) {
        [TMProgressHUD showInfoWithStyleDarkStatus:@"请选择购买的商品！"];
        return;
    }
    bool canBuy = YES;
    for (TMMyCartModel *model in self.resultArray) {
        if (model.under.integerValue == 0) {
            canBuy = NO;
        }
    }
    if (!canBuy) {
        [TMProgressHUD showInfoWithStyleDarkStatus:@"已经下架的商品不能再结算啦"];
        return;
    }
    TMBuyGoodsController *vc = [[UIStoryboard storyboardWithName:@"Nearby" bundle:nil] instantiateViewControllerWithIdentifier:@"TMBuyGoodsController"];
    NSMutableArray *dic = [NSMutableArray array];
    NSMutableArray *carid = [NSMutableArray array];
    vc.isFromBuy = NO;
    for (TMMyCartModel *models in self.resultArray) {
        [dic addObject:[NSString stringWithFormat:@"%ld", models.cid]];
        [carid addObject:[NSString stringWithFormat:@"%ld", models.coid]];
        
    }
    vc.listDic = dic;
    vc.caridArray = carid;
    [self.navigationController pushViewController:vc animated:YES];
    
}
- (void)showAlertWith:(id) index AndAll:(BOOL)isall{
    UIAlertController *alert =  [UIAlertController alertControllerWithTitle:isall ?@"是否删除所有商品" :@"是否删除该商品" message:nil preferredStyle:UIAlertControllerStyleAlert handler:^(UIAlertAction * _Nonnull action) {
        if ([action.title isEqualToString:@"确认"]) {
            [self.viewModel deleteShoppingCartParam:index Success:^(id responseObject) {
                [self.shoppingTab.mj_header beginRefreshing];
                 [self noResultViewShowORNot];
                if (isall ==YES || self.is_checkAll == NO) {
                     [self displayStates:NO];
                }
                self.totalPriceLabel.text = [NSString stringWithFormat:@"0元"];
                self.checkAllBtn.selected = NO;
            } Failed:^(NSString *error) {
                 [self noResultViewShowORNot];
            }];
        }else{
            [[SPToolSet currentViewController] dismissViewControllerAnimated:YES completion:nil];
        }
    } cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
    [[SPToolSet currentViewController] presentViewController:alert animated:YES completion:^{
        
    }];
}
- (IBAction)deleteAllAction:(UIButton *)sender {
    if (!self.resultArray.count) {
        [TMProgressHUD showInfoWithStyleDarkStatus:@"请选择删除的商品！"];
        return;
    }
    NSMutableArray *list = [NSMutableArray array];
    for (TMMyCartModel *models in self.resultArray) {
        [list addObject:[NSString stringWithFormat:@"%ld", models.coid]];
    }
     NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:list options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    [self showAlertWith:jsonString AndAll:YES];
}

@end
